<?php
namespace Stevenyangecho\UEditor;

use OSS\OssClient;
use OSS\Core\OssException;


class Oss
{
    public $accessKeyId = "";
    public $accessKeySecret = "";
    public $endpoint = "";
    public $bucket = '';
    public $ossClient = '';


    public function __construct()
    {
        $this->accessKeyId = config('UEditorUpload.core.aliyun.accessKeyId');
        $this->accessKeySecret = config('UEditorUpload.core.aliyun.accessKeySecret');
        $this->endpoint = config('UEditorUpload.core.aliyun.endpoint');
        $this->bucket = config('UEditorUpload.core.aliyun.bucket');
        $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, false);

    }

    /**
     * 把本地变量的内容到文件
     * 简单上传,上传指定变量的内存值作为object的内容
     */
    public function putObject($object, $imgPath)
    {
        $content = file_get_contents($imgPath); // 把当前文件的内容获取到传入文件中
        $options = array();
        try {
            $this->ossClient->putObject($this->bucket, $object, $content, $options);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return TRUE;
    }

    /**
     * 上传指定的本地文件内容
     */
    public function uploadFile($imgPath, $object) //$_FILES['img']['tmp_name']
    {
        $filePath = $imgPath;
        $options = array();
        try {
            $this->ossClient->uploadFile($this->bucket, $object, $filePath, $options);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return TRUE;
    }

    // 删除对象
    public function deleteObject($object)
    {
        try {
            $this->ossClient->deleteObject($this->bucket, $object);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return TRUE;
    }

    // 判断对象是否存在
    public function doesObjectExist($object)
    {
        try {
            $result = $this->ossClient->doesObjectExist($this->bucket, $object);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return $result;
    }

    // 批量删除对象
    public function deleteObjects($objects)
    {
        try {
            $this->ossClient->deleteObjects($this->bucket, $objects);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return TRUE;
    }

    /**
     * 获取object的内容
     *
     * @param OssClient $ossClient OssClient实例
     * @param string $bucket 存储空间名称
     * @return null
     */
    public function getObject($object)
    {
        $options = array();
        try {
            $content = $this->ossClient->getObject($this->bucket, $object, $options);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        // file_get_contents
        return $content;
    }
}